import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    value: '',
    suggest: [],
    // 搜索历史
    searchHistory: []
  }

  config = {
  }

  methods = {
    async onChange(e) {
      this.value = e.detail.trim()
      if (!e.detail.trim().length) return this.suggest = []
      const { data: res } = await wepy.get('/goods/qsearch', { query: e.detail })
      wepy.baseToast(res)
      console.log(res);
      this.suggest = res.message
      this.$apply()
    },
    onSearch(e) {
      const kw = e.detail.trim()
      if (!kw.length) return
      if (this.searchHistory.indexOf(kw) === -1) {
        this.searchHistory.unshift(kw)
      }
      this.searchHistory = this.searchHistory.slice(0, 10)
      wepy.setStorageSync('sH', this.searchHistory)
      this.value = ''
      wepy.navigateTo({
        url: `/pages/goods_list?query=${kw}`
      })
    },
    onCancel() {
      this.suggest = []
    },
    // 导航到详情页
    goToDetail(id) {
      wepy.navigateTo({
        url: `/pages/goods_detail/main?goods_id=${id}`
      })
    },
    // 点击搜索记录标签前往详情页
    tagToDetail(query) {
      wepy.navigateTo({
        url: `/pages/goods_detail/main?query=${query}`
      })
    },
    // 清空搜索记录
    deleteHistory() {
      this.searchHistory = []
      wepy.setStorageSync('sH', [])
    }
  }
  computed = {
    // 是否显示搜索历史
    isShowHistory() {
      if (this.value.length <= 0) {
        return false
      }
      return true
    }
  }

  onLoad() {
    const sH = wepy.getStorageSync('sH') || []
    this.searchHistory = sH
  }
  onShow() {
    this.$parent.changeBandge()
  }
}
